package com.tuju.jetpackfirstdemo.ui.processes;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Service;
import android.app.usage.UsageEvents;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.jaredrummler.android.processes.AndroidProcesses;
import com.jaredrummler.android.processes.models.AndroidAppProcess;
import com.jaredrummler.android.processes.models.Stat;
import com.jaredrummler.android.processes.models.Statm;
import com.tuju.jetpackfirstdemo.R;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

public class RunningProcessActivity extends AppCompatActivity {

    private EditText et_print;
    private Button btn_process;
    private Handler mHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_running_process);
        et_print = findViewById(R.id.et_print);
        btn_process = findViewById(R.id.btn_process);
    }

    //监听所有进程2
    public void listenerProcess(View view) {
        ArrayList<ProcessInfo> processInfos = getProcessInfo(this);
        if (processInfos == null || processInfos.isEmpty()) {
            Toast.makeText(this, "没有正在运行进程...", Toast.LENGTH_SHORT).show();
        }
        StringBuffer sb = new StringBuffer();
        for (ProcessInfo processInfo : processInfos) {
            sb.append(">>进程名：" + processInfo.name);
            sb.append(" \n");
            sb.append(" packageName:" + processInfo.packageName);
            sb.append(" \n");
            sb.append(" memory:" + processInfo.memory);
            sb.append(" \n");
            sb.append(" isUser:" + processInfo.isUser);
            sb.append(" icon:" + processInfo.icon);
        }
        print(sb.toString());
    }

    /**
     * 新API获取进程信息
     */
    public void listenerProcess3(View view) {
        //检查权限
        if (hasEnable(this)) {
            getProcess3(this);
        } else {
            Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
            intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.Settings$SecuritySettingsActivity"));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }

    private String getProcess3(Context context) {
        if (Build.VERSION.SDK_INT >= 21) {
            try {
                // 根据最近time_ms毫秒内的应用统计信息进行排序获取当前顶端的包名
                long time = System.currentTimeMillis();
                UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
                // 这里返回了在time_ms时间内系统所有的进程列表
                // 如果有获取系统的一段时间之内进程的需要可以打印出每个包名
                long time_ms = 10000;//10秒内
                List<UsageStats> usageStatsList = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST
                        , time - time_ms, time);
                // 使用queryEvents
                // List<UsageStats> queryUsageStats =  usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, 0, time);
                // UsageEvents usageEvents = usageStatsManager.queryEvents(isInit ? 0 : time-time_ms, time);

                //  这里使用的是usageEvent来获取顶端包名
//                String result = "";
//                UsageEvents.Event event = new UsageEvents.Event();
//                UsageEvents usageEvents = usageStatsManager.queryEvents(time - 500, time);
//                while (usageEvents.hasNextEvent()) {
//                    usageEvents.getNextEvent(event);
//                    if (event.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
//                        result = event.getPackageName();
//                        Log.e("test", "##当前顶端应用包名:" + result);
//                    }
//                }
                StringBuffer sb = new StringBuffer();
                if (usageStatsList != null && usageStatsList.size() > 0) {
                    SortedMap<Long, UsageStats> runningTask = new TreeMap<>();
                    for (UsageStats usageStats : usageStatsList) {
                        sb.append(usageStats.getPackageName());
                        Log.i("yanze_pkgName", usageStats.getPackageName());
                        runningTask.put(usageStats.getLastTimeUsed(), usageStats);
                    }
                    if (runningTask.isEmpty()) {
                        return null;
                    }
                    String topPackageName = runningTask.get(runningTask.lastKey()).getPackageName();
                    sb.append("##当前顶端应用包名:" + topPackageName);
                    Log.i("yanze_pkgName", "##当前顶端应用包名:" + topPackageName);
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    @SuppressLint("NewApi")
    public static boolean hasEnable(Context context) {
//        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {   // 如果大于等于5.0 再做判断
//            long ts = System.currentTimeMillis();
//            UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Service.USAGE_STATS_SERVICE);
//            List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, 0, ts);
//            if (queryUsageStats == null || queryUsageStats.isEmpty()) {
//                return false;
//            }
//        }
        return true;
    }


    /**
     * 三方库获取进程信息
     */
    public void getRunningProcess(View view) {
        PackageManager pm = getPackageManager();
        // Get a list of running apps
        List<AndroidAppProcess> processes = AndroidProcesses.getRunningAppProcesses();

        for (AndroidAppProcess process : processes) {
            // Get some information about the process
            StringBuffer sb = new StringBuffer();
            String processName = process.name;
            sb.append(">>进程名：" + processName);
            try {
                Stat stat = process.stat();
                int pid = stat.getPid();
                int parentProcessId = stat.ppid();
                long startTime = stat.stime();
                int policy = stat.policy();
                char state = stat.state();
                sb.append(" \n");
                sb.append(" Stat:");
                sb.append(" pid:" + pid);
                sb.append(" parentProcessId:" + parentProcessId);
                sb.append(" startTime:" + startTime);
                sb.append(" policy:" + policy);
                sb.append(" state:" + state);

                Statm statm = process.statm();
                long totalSizeOfProcess = statm.getSize();
                long residentSetSize = statm.getResidentSetSize();
                sb.append(" \n");
                sb.append(" totalSizeOfProcess:" + totalSizeOfProcess);
                sb.append(" residentSetSize:" + residentSetSize);

                PackageInfo packageInfo = process.getPackageInfo(this, 0);
                String appName = packageInfo.applicationInfo.loadLabel(pm).toString();
                sb.append(" \n");
                sb.append(" appName:" + appName);

                print(sb.toString());
            } catch (IOException | PackageManager.NameNotFoundException e) {
                Toast.makeText(this, "error:" + e.getMessage(), Toast.LENGTH_SHORT).show();
                print("error:" + e.getMessage());
            }
        }
    }

    /**
     * 获取正在运行的进程信息2
     */
    @Deprecated
    public ArrayList<ProcessInfo> getProcessInfo(Context context) {
        // 存放全部信息
        ArrayList<ProcessInfo> infos = new ArrayList<>();
        // 获取活动管理器
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        PackageManager packageManager = context.getPackageManager();
        // 获取正在运行的进程信息
        List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = am
                .getRunningAppProcesses();
        // 遍历所有 进程
        for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo : runningAppProcesses) {
            // 进程名字 一般和包名一样
            String processName = runningAppProcessInfo.processName;
            // 进程的id
            int pid = runningAppProcessInfo.pid;
            Drawable icon = null;
            String name = null;
            long memSize = 0;
            boolean isSys = false;
            try {
                // 获取一个应用的ApplicationInfo 对象
                ApplicationInfo applicationInfo = packageManager
                        .getApplicationInfo(processName, 0);
                icon = applicationInfo.loadIcon(packageManager);// 图片
                name = applicationInfo.loadLabel(packageManager).toString();// 名字
                if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == ApplicationInfo.FLAG_SYSTEM) {
                    // 是系统进程
                    isSys = true;
                } else {
                    // 是用户进程
                    isSys = false;
                }
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
                // 包名:am
                // 系统进程
                // 给一些默认值
                name = processName;
                icon = context.getResources().getDrawable(
                        R.drawable.ic_launcher_foreground);
                // 认为是系统进程
                isSys = true;
            }
            int[] pids = new int[]{pid};
            // 获取指定pid的进程内存信息 这里可以获取多个
            android.os.Debug.MemoryInfo[] processMemoryInfo = am
                    .getProcessMemoryInfo(pids);
            // 获取内存大小
            memSize = processMemoryInfo[0].getTotalPss() * 1024;
            ProcessInfo info = new ProcessInfo(name, icon, memSize, isSys, processName);
            infos.add(info);
        }
        return infos;
    }

    public class ProcessInfo {
        public String name;
        public String packageName;
        public Drawable icon;
        public long memory;
        public boolean isUser; //true表示用户进程

        public ProcessInfo(String name, Drawable icon, long memory, boolean isUser, String packageName) {
            this.name = name;
            this.icon = icon;
            this.memory = memory;
            this.isUser = isUser;
            this.packageName = packageName;
        }
    }


    /**
     * 打印信息
     */
    private void print(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                StringBuffer sb = new StringBuffer();
                sb.append((msg == null) ? "" : msg);
                sb.append("\n");
                String oldContant = et_print.getText().toString();
                et_print.setText(sb.toString() + oldContant);
            }
        });
    }

    public void clear(View view) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                et_print.setText("");
            }
        });
    }
}
